package com.hulk.dryad.manage.framework.websocket.server.cluster;

import com.hulk.dryad.common.constant.CommonConstants;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * websocket
 *
 * @author
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ClusterWebSocketConfiguration.class)
@AutoConfigureAfter({ClusterWebSocketConfiguration.class,RedisAutoConfiguration.class})
@EnableConfigurationProperties(ClusterWebSocketProperties.class)
public class RedisMessageConfiguration {

	/**
	 * 消息监听器，使用MessageAdapter可实现自动化解码及方法代理
	 *
	 * @param clusterWebSocketSender clusterWebSocketSender
	 * @return ClusterWebSocketMessageListener
	 */
	@Bean
	public RedisWebSocketMessageListener webSocketClusterMessageListener(ClusterWebSocketSender clusterWebSocketSender) {
		return new RedisWebSocketMessageListener(clusterWebSocketSender);
	}

	/**
	 * 将订阅器绑定到容器
	 *
	 * @param environment       environment
	 * @param connectionFactory RedisConnectionFactory
	 * @param messageListener   ClusterWebSocketMessageListener
	 * @return RedisMessageListenerContainer
	 */
	@Bean
	public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
												   Environment environment,
												   ClusterWebSocketProperties clusterProperties,
												   RedisWebSocketMessageListener messageListener) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		String redisSubTopic = getRedisSubTopic(environment, clusterProperties);
		container.addMessageListener(messageListener, new PatternTopic(redisSubTopic));
		return container;
	}

	private static String getRedisSubTopic(Environment environment, ClusterWebSocketProperties properties) {
		return properties.getRedisSubTopicPrefix() + environment.getProperty(CommonConstants.SPRING_APP_NAME_KEY);
	}
}
